//
//  AppDelegate+Landscape.m
//  ZLClient
//
//  Created by lizhu on 2017/5/11.
//  Copyright © 2017年 zhuli. All rights reserved.
//

#import "AppDelegate+Landscape.h"
#import <objc/runtime.h>

@implementation AppDelegate (Landscape)
#pragma mark - life cycles
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window{
    return self.appOrientation;
}

#pragma mark - public methods
- (void)applicationLandscape:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    //landscape
    self.appOrientation=UIInterfaceOrientationMaskPortrait;
    [self addObserver:self forKeyPath:NSStringFromSelector(@selector(appOrientation)) options:NSKeyValueObservingOptionNew context:nil];
}

#pragma mark - KVO
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    if ([keyPath isEqualToString:NSStringFromSelector(@selector(appOrientation))]) {
        [self application:[UIApplication sharedApplication] supportedInterfaceOrientationsForWindow:self.window];
    }
}

- (void)dealloc{
    [self removeObserver:self forKeyPath:NSStringFromSelector(@selector(appOrientation))];
}

#pragma mark - getters and setters
- (UIInterfaceOrientationMask)appOrientation{
    return [objc_getAssociatedObject(self, _cmd) intValue];//object转int
}

- (void)setAppOrientation:(UIInterfaceOrientationMask)appOrientation{
    objc_setAssociatedObject(self, @selector(appOrientation), @(appOrientation), OBJC_ASSOCIATION_ASSIGN);
    if (appOrientation==UIInterfaceOrientationMaskPortrait) {//强制竖屏
        //        if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
        //            [[UIDevice currentDevice] performSelector:@selector(setOrientation:) withObject:@(UIInterfaceOrientationPortrait)];
        //        }
        if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
            SEL selector = @selector(setOrientation:);
            NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
            [invocation setSelector:selector];
            [invocation setTarget:[UIDevice currentDevice]];
            [invocation setArgument:&appOrientation atIndex:2];
            [invocation invoke];
        }
    }
}
@end
